package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.AtMessage;
import com.kaishengit.entity.Message;
import com.kaishengit.entity.User;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.Page;
import com.kaishengit.util.RowMapper;

public class AtMessageDao {
	private DBHelp<AtMessage> db = new DBHelp<AtMessage>();
	public void save(String mid, String id, String projectid) {
		String sql = "insert into t_atmessage(t_message_id,t_user_id,t_project_id) values(?,?,?)";
		db.executeSQL(sql, mid,id,projectid);
		
	}
	public Page<AtMessage> findByUserId(String id, Page<AtMessage> page) {
		StringBuilder sql = new StringBuilder();
		sql.append("select ta.t_message_id,ta.t_user_id as myid,ta.t_project_id ,tm.content,tm.date,tm.t_user_id,tm.t_project_id,tu.username,tu.imgname from t_atmessage as ta ");
		sql.append("left join t_message as tm on tm.id = ta.t_message_id ");
		sql.append("left join t_user as tu on tu.id = tm.t_user_id ");
		sql.append("where ta.t_user_id = ? limit ?,?");
		List<AtMessage> list =  db.executeQueryForList(sql.toString(), new AtMessageRowMapper(),id,page.getOffest(),page.getPageSize() );
		page.setList(list);
		return page;
		
		
	}
	public long findCount(String id) {
		String sql = "select count(*) from t_atmessage where t_user_id = ?";
		return (Long) db.executeForFunction(sql, id);
	}
	private class AtMessageRowMapper implements RowMapper<AtMessage>{

		public AtMessage mapRow(ResultSet rs) throws SQLException {
			AtMessage am = new AtMessage();
			am.setMessageid(rs.getString("t_message_id"));
			am.setProjectid(rs.getString("t_project_id"));
			am.setUserid(rs.getString("myid"));
			
			Message message = new Message();
			message.setId(rs.getString("t_message_id"));
			message.setContent(rs.getString("content"));
			message.setDate(rs.getString("date"));
			
			User user = new User();
			user.setId(rs.getString("t_user_id"));
			user.setImgname(rs.getString("imgname"));
			user.setUsername(rs.getString("username"));
			
			message.setUser(user);
			
			am.setMessage(message);
			return am;
			
		}
		
		
		
	}
}
